package com.bw.ppjokeplay.mvvm.view
import android.app.Service
import android.content.Intent
import android.os.Binder
import android.os.Handler
import android.os.IBinder
import okhttp3.*

/**
 * @author Lishaohe
 * @description:
 * @date :2021/11/18 0018 下午 6:54
 *
 */
class WebSocketService : Service() {

    private lateinit var websocket : WebSocket
    private var linkedFlag = false//记录websocket连接状态
    private var delayTime : Long = 10*1000//间隔10s重连websocket服务器
    private var handler : Handler = Handler()
    private lateinit var msgCallBack: MsgCallBack

    override fun onCreate() {
        super.onCreate()
        open()
    }

    override fun onDestroy() {
        super.onDestroy()
        closeWebSocket()
    }
////
    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        return START_STICKY
        //设置服务粘滞，服务在终止时会自启动一次
    }

    //设置msgCallBack对象
    fun setMsgCall(callBack: MsgCallBack){
        msgCallBack = callBack
    }
    //连接websocket
    private fun open(){
        var request : Request = Request.Builder().url(LiveConst.WEBSOCKETURL).build()
        websocket = OkHttpClient.Builder().build().newWebSocket(request,MsgListener())
    }
    //重连websocket
    private fun resetConnect(){
        open()
    }
    //断开websocket
    fun closeWebSocket(){
        if (websocket!=null&&linkedFlag){
            websocket.close(0,"close")
        }
    }
    //发消息
    fun sendMsg(msg : String){
        if (websocket!=null&&linkedFlag){
            websocket.send(msg)
        }
    }

    //websocket监听器
    inner class MsgListener : WebSocketListener(){
        //开启连接
        override fun onOpen(webSocket: WebSocket, response: Response) {
            super.onOpen(webSocket, response)
            var responseStr : String = response.body().toString()
            if (responseStr.equals("连接成功")){
                linkedFlag = true
            }
        }

        //报错
        override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {
            super.onFailure(webSocket, t, response)
            handler.postDelayed(object : Runnable{
                override fun run() {
                    //连接失败->重连
                    resetConnect()
                }

            },delayTime)
        }

        //关闭
        override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {
            super.onClosed(webSocket, code, reason)
        }

        //接收服务器下发消息
        override fun onMessage(webSocket: WebSocket, text: String) {
            super.onMessage(webSocket, text)
            //切换线程到主线程->okhttp发起的socket连接
            //网络请求->子线程执行->执行结果->子线程
            //获取到服务器推送消息->传递消息到activity
            if (msgCallBack!=null){
                msgCallBack.msgCall(text)
            }
        }

    }

    override fun onBind(intent: Intent?): IBinder? {
        return WebSocketBinder()
    }

    inner class WebSocketBinder : Binder(){
        fun getWebSocketService():WebSocketService{
            return this@WebSocketService
        }
    }


}